import skimage
from skimage import util
import cv2
import numpy as np
from matplotlib import pyplot as plt


# 高斯噪声函数,mean:均值；var：方差
def gasuss_noise(image, mean=0, var=0.01):
    image = np.array(image / 255, dtype=float)
    noise = np.random.normal(mean, var ** 0.5, img.shape)
    img_noise = image + noise
    if img_noise.min() < 0:
        low_clip = -1
    else:
        low_clip = 0
    img_noise = np.clip(img_noise, low_clip, 1.0)
    img_noise = np.uint8(img_noise * 255)
    return img_noise


# 随机噪声，image：原图像；noise_num：添加噪音点数目
def random_noise(image, noise_num):
    img_noise = image
    rows, cols, chn = img_noise.shape
    # 加噪声
    for i in range(noise_num):
        # 随机生成指定范围的整数
        x = np.random.randint(0, rows)
        y = np.random.randint(0, cols)
        img_noise[x, y, :] = 255
    return img_noise


img = cv2.imread(r"C:\Users\Public\opencv\Figure\lena.png")
img = np.array(img)

# 高斯噪声
noise_gs_img = gasuss_noise(img, mean=0, var=0.01)

# 椒盐噪声
noise_sp_img = util.random_noise(img, mode='s&p')

# 随机噪声
img_random_noise = random_noise(img, 1000)

# 柏松噪音
noise_sp_img = util.random_noise(img, mode='poisson')

# 显示图像
plt.subplot(231), plt.imshow(img)
plt.subplot(232), plt.imshow(noise_gs_img)
plt.subplot(233), plt.imshow(noise_sp_img)
plt.subplot(234), plt.imshow(img_random_noise)
plt.subplot(235), plt.imshow(noise_sp_img)
cv2.waitKey(0)
cv2.destroyAllWindows()